package de.damontools.awolowa.gui;

import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import greendroid.widget.ActionBarItem.Type;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.ToggleButton;
import de.damontools.awolowa.R;
import de.damontools.awolowa.application.Profile;
import de.damontools.awolowa.application.WakeOnLan;
import de.damontools.awolowa.db.DatabaseManager;

public class ProfileActivity extends GDActivity implements OnClickListener {
	// GUI views
	EditText mProfileName;
	Spinner mSpinnerSSID;
	EditText mEditMAC;
	ToggleButton mToggleActive;
	Button mButtonSend;
//	InetAddress mIpAdress;
//	int mPort;

	private static final int ACTION_BAR_APPLY = 0;

	private static WifiManager wifi;
	private static List<String> ssidList = new ArrayList<String>();

	// Database
	private DatabaseManager mDatabaseManager = null;

	// Called when the activity is first created
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mDatabaseManager = new DatabaseManager(this);
		
		setActionBarContentView(R.layout.activity_new);
		setTitle(R.string.title_new);

		addActionBarItem(Type.Add, ACTION_BAR_APPLY);

		

		getReferences();
		setListeners();
		checkWifis();

		mProfileName.setHint(mSpinnerSSID.getSelectedItem().toString());
	}

	@Override
	public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
		switch (item.getItemId()) {
			case ACTION_BAR_APPLY:
				saveProfile();
				break;
			default:
				return super.onHandleActionBarItemClick(item, position);
		}
		return true;
	}

	/**
	 * @param savedInstanceState
	 * 
	 */
	private void setListeners() {
		/*mButtonSend.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if (checkMAC()){
					try {
						WakeOnLan.wakeup(mEditMAC.getText().toString());
						Log.d("awolowa", "sending: " + mEditMAC.getText().toString() );
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		});*/
		
		mSpinnerSSID.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				mProfileName.setHint(mSpinnerSSID.getSelectedItem().toString());
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		refreshGUI();
	}

	private void getReferences() {
		mProfileName = (EditText) findViewById(R.id.editProfileName);
		mSpinnerSSID = (Spinner) findViewById(R.id.spinnerSSID);
		mEditMAC = (EditText) findViewById(R.id.editMAC);
		mToggleActive = (ToggleButton) findViewById(R.id.toggleActive);
		mButtonSend = (Button) findViewById(R.id.buttonSendWoL);
		// todo: get ip and port from options
//		try {
//			mIpAdress = InetAddress.getByName("255.255.255.255");
////			mIpAdress = mIpAdress.getHostAddress();
//		} catch (UnknownHostException e) {
//			e.printStackTrace();
//		}
//		mPort = 7;
	}

	public void saveProfile() {

		if (checkMAC()){
			if (mProfileName.getText().toString().length() == 0) {
				mProfileName.setText(mSpinnerSSID.getSelectedItem().toString());
			}
			Profile profile = new Profile(mProfileName.getText().toString(), mSpinnerSSID.getSelectedItem().toString(), mEditMAC.getText().toString(), 3, "false", mToggleActive.isChecked());
			mDatabaseManager.addProfile(profile);
			startActivity(new Intent(getApplicationContext(), ProfileListActivity.class));
		}

	}
	
	private boolean checkMAC(){
		if (mEditMAC.getText().toString().length() == 0) {
			mEditMAC.setError("MAC adress is required!");
			return false;
		}else{
			return true;
		}
	}

	/**
	 * Refresh GUI with database contents
	 */
	private void refreshGUI() {
		// Used to store database contents
		StringBuilder buf = new StringBuilder();

		// Set new text
		mEditMAC.setText(buf.toString());
	}

	/**
	 * Check the available Wifis
	 */
	private void checkWifis() {
		setWifi((WifiManager) getSystemService(Context.WIFI_SERVICE));

		ssidList.clear();
		for (WifiConfiguration wifilist : getWifi().getConfiguredNetworks()) {
			ssidList.add(wifilist.SSID.toString().replace("\"", ""));
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ssidList); 
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSpinnerSSID.setAdapter(adapter);
	}

	/**
	 * @return the wifi
	 */
	public static WifiManager getWifi() {
		return wifi;
	}

	/**
	 * @param wifi
	 *            the wifi to set
	 */
	public static void setWifi(WifiManager wifi) {
		ProfileActivity.wifi = wifi;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}



}
